package org.springframework.boot.dcj.config;

import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate;
import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;

@Configuration
@Slf4j
public class RestConfiguration {
    @Bean
    @SentinelRestTemplate(blockHandler = "handleBlock", blockHandlerClass = ExceptionUtil.class,
            fallbackClass = ExceptionUtil.class, fallback = "fallBack"
    )
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static class ExceptionUtil {
        public static SentinelClientHttpResponse handleBlock(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException be) {
            return new SentinelClientHttpResponse("handleBlock");
        }

        public static SentinelClientHttpResponse fallBack(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException be) {
            return new SentinelClientHttpResponse("fallBack");
        }

    }
}
